<script setup lang="ts">
import { ref, h } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchCollectionRuleList, deleteCollectionRule, enableCollectionRule, disableCollectionRule, triggerCollectionTask } from '@/service/api';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import RuleOperateDrawer from './modules/rule-operate-drawer.vue';

const appStore = useAppStore();

const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchCollectionRuleList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    ruleName: null,
    ruleCode: null,
    fileType: null,
    sourceType: null,
    status: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: '序号',
      align: 'center',
      width: 64
    },
    {
      key: 'ruleName',
      title: '规则名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'ruleCode',
      title: '规则编码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'fileType',
      title: '文件类型',
      align: 'center',
      width: 100,
      render: row => {
        return h(NTag, { type: 'info' }, { default: () => row.fileType });
      }
    },
    {
      key: 'sourceType',
      title: '来源类型',
      align: 'center',
      width: 100,
      render: row => {
        const typeMap: Record<string, string> = {
          LOCAL: '本地',
          FTP: 'FTP',
          SFTP: 'SFTP',
          HTTP: 'HTTP',
          OSS: '对象存储'
        };
        return h(NTag, { type: 'success' }, { default: () => typeMap[row.sourceType] || row.sourceType });
      }
    },
    {
      key: 'scheduleType',
      title: '调度类型',
      align: 'center',
      width: 100,
      render: row => {
        const typeMap: Record<string, string> = {
          REALTIME: '实时',
          HOURLY: '每小时',
          DAILY: '每天',
          WEEKLY: '每周',
          MONTHLY: '每月',
          MANUAL: '手动'
        };
        return typeMap[row.scheduleType] || row.scheduleType;
      }
    },
    {
      key: 'targetDatabase',
      title: '目标数据库',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'targetTable',
      title: '目标表',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 80,
      render: row => {
        const isEnabled = row.status === 'ENABLED';
        return h(
          NTag,
          { type: isEnabled ? 'success' : 'default' },
          { default: () => (isEnabled ? '已启用' : '已禁用') }
        );
      }
    },
    {
      key: 'createTime',
      title: '创建时间',
      align: 'center',
      width: 180
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 280,
      render: row => {
        return h(
          NSpace,
          { justify: 'center' },
          {
            default: () => [
              h(
                NButton,
                {
                  size: 'small',
                  onClick: () => handleEdit(row.id)
                },
                { default: () => '编辑' }
              ),
              row.status === 'DISABLED'
                ? h(
                    NButton,
                    {
                      size: 'small',
                      type: 'success',
                      onClick: () => handleEnable(row.id)
                    },
                    { default: () => '启用' }
                  )
                : h(
                    NButton,
                    {
                      size: 'small',
                      type: 'warning',
                      onClick: () => handleDisable(row.id)
                    },
                    { default: () => '禁用' }
                  ),
              h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  onClick: () => handleTrigger(row.id)
                },
                { default: () => '触发' }
              ),
              h(
                NPopconfirm,
                {
                  onPositiveClick: () => handleDelete(row.id)
                },
                {
                  default: () => '确认删除？',
                  trigger: () =>
                    h(
                      NButton,
                      {
                        size: 'small',
                        type: 'error'
                      },
                      { default: () => '删除' }
                    )
                }
              )
            ]
          }
        );
      }
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // @ts-ignore
} = useTableOperate(data, getData);

async function handleDelete(id: number) {
  await onDeleted(deleteCollectionRule, id);
}

async function handleEnable(id: number) {
  await enableCollectionRule(id);
  window.$message?.success('启用成功');
  getData();
}

async function handleDisable(id: number) {
  await disableCollectionRule(id);
  window.$message?.success('禁用成功');
  getData();
}

async function handleTrigger(id: number) {
  const { data: taskId, error } = await triggerCollectionTask(id);
  if (!error) {
    window.$message?.success(`触发成功，任务ID: ${taskId}`);
  }
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="采集规则管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="onBatchDeleted(deleteCollectionRule, checkedRowKeys)"
          @refresh="getData"
        />
      </template>
      <NSpace class="pb-12px" justify="space-between">
        <NSpace>
          <NInput v-model:value="searchParams.ruleName" placeholder="规则名称" clearable />
          <NInput v-model:value="searchParams.ruleCode" placeholder="规则编码" clearable />
          <NSelect
            v-model:value="searchParams.fileType"
            placeholder="文件类型"
            clearable
            :options="[
              { label: 'CSV', value: 'CSV' },
              { label: 'Excel(XLS)', value: 'XLS' },
              { label: 'Excel(XLSX)', value: 'XLSX' },
              { label: 'XML', value: 'XML' },
              { label: 'JSON', value: 'JSON' },
              { label: 'SQL脚本', value: 'SQL' }
            ]"
            style="width: 150px"
          />
          <NSelect
            v-model:value="searchParams.status"
            placeholder="状态"
            clearable
            :options="[
              { label: '已启用', value: 'ENABLED' },
              { label: '已禁用', value: 'DISABLED' }
            ]"
            style="width: 120px"
          />
          <NButton type="primary" ghost @click="getData">
            <icon-ic-round-search class="mr-4px text-20px" />
            搜索
          </NButton>
          <NButton @click="resetSearchParams">
            <icon-ic-round-refresh class="mr-4px text-20px" />
            重置
          </NButton>
        </NSpace>
      </NSpace>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1400"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <RuleOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
